package com.goldgov.basedata.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gtiles.components.securityworkbench.bean.SwbAuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.goldgov.authorityInfo.service.AuthorityInfoInit;
import com.goldgov.basedata.service.BaseData;
import com.goldgov.basedata.service.BaseDataOrg;
import com.goldgov.basedata.service.BaseDataQuery;
import com.goldgov.basedata.service.BaseDataService;
import com.goldgov.basedata.service.DataType;
import com.goldgov.basedata.service.DataTypeQuery;
import com.goldgov.basedata.service.DataTypeService;
import com.goldgov.basedata.service.IBaseDataOrgService;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.utils.JsonUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: BaseDataController 
 * @Description: TODO
 * @author MaN
 * @date 2018年7月5日 
 */

@RestController
@RequestMapping("/workbench/baseData")
@Api("数据字典接口")
public class BaseDataController {

	@Autowired
	private BaseDataService baseDataService;
	@Autowired
	private DataTypeService dataTypeService;
	
	@Autowired
	private IBaseDataOrgService baseDataOrgService;
	
	@PostMapping("/addBaseData")
	@ApiOperation(value = "新增数据字典", notes ="")
	public JsonObject<Object> addBaseData(BaseData obj,HttpServletRequest request){
		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
	//	SwbAuthUser u=LoginAuthUser.getUserByAdminTest(request);
		//未传入orgID时默认加入到该管理员所在机构
		if(obj!=null&&(obj.getOrgID()==null||"".equals(obj.getOrgID()))) {
			String scopeCode=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
			if(scopeCode!=null&&!"".equals(scopeCode.trim())) {
			String orgID=baseDataService.findOrgIdByScopeCode(scopeCode);
			obj.setOrgID(orgID);
			}else {
				obj.setOrgID("-1");
			}
		}
		obj.setUserID(u.getEntityID());//发布人id
		obj.setActiveStatus(BaseDataQuery.ACTIVESTATE_YES);
		obj.setLastModifyTime(new Date());
		//查询当前编码下是否已存在改字典
		BaseDataQuery query=new BaseDataQuery();
		query.setSearchDataKey(obj.getDataKey());
		query.setSearchTypeCode(obj.getTypeCode());
		List<BaseData> list=baseDataService.findBaseDataList(query);
		if(list!=null&&list.size()>0) {
			String value=list.get(0).getDataValue();
			if(obj.getDataValue().equals(value)) {
				baseDataService.addBaseData(obj);
			}else {
				return JsonUtil.error("当前字典编码已存在,请联系管理员下发字典或修改编码");
			}
		}
		baseDataService.addBaseData(obj);
		return JsonSuccessObject.SUCCESS;
	}
	
	@GetMapping("/listBaseData")
	@ApiOperation(value = "数据字典列表", notes ="")
	//@ApiImplicitParams({@ApiImplicitParam(name = "searchTypeID", value = "类型id", paramType = "query")})
	public JsonQueryObject<BaseData> listBaseData( BaseDataQuery query,HttpServletRequest request){
		if(query.getSearchScopeCodeEq()==null||"".equals(query.getSearchScopeCodeEq().trim())) {
			String scopeCode=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
			if(scopeCode!=null&&!"".equals(scopeCode.trim())) {
				query.setSearchScopeCodeEq(scopeCode);
			}else {
				query.setSearchScopeCode("root");
			}
		}
		List<BaseData> list=baseDataService.getBaseDataList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	@PostMapping("/updateBaseData")
	@ApiOperation(value = "修改数据字典", notes ="")
	public JsonObject<Object> updateBaseData(BaseData obj,HttpServletRequest request){
		obj.setLastModifyTime(new Date());
		//查询编码是否已存在
		BaseDataQuery query=new BaseDataQuery();
		query.setSearchDataKey(obj.getDataKey());
		query.setSearchTypeCode(obj.getTypeCode());
		List<BaseData> list=baseDataService.findBaseDataList(query);
		if(list!=null&&list.size()>0) {
			String id=list.get(0).getDataID();
			if(!obj.getDataID().endsWith(id)) {
				return JsonUtil.error("当前字典编码已存在");
			}
		}
		baseDataService.updateBaseData(obj);
		return JsonSuccessObject.SUCCESS;
	}
	@GetMapping("/deleteBaseData")
	@ApiOperation(value = "删除数据字典", notes = "")
	public JsonObject<Object> replyExport(@ApiParam(value = "dataID", required = true) @RequestParam("dataID") String dataID,String organizationId,HttpServletRequest request,HttpServletResponse response) throws Exception {
		//删除先删关联关系，如果关联为空则删除字典
		int count=	baseDataOrgService.deleteBaseDataOrg(new String[] {dataID}, organizationId);
		if(count>0) {
			Integer total=baseDataOrgService.findBaseDataOrgCount(dataID, null);
			if(total==0) baseDataService.deleteBaseData(dataID);	
		}
		return JsonSuccessObject.SUCCESS;
	}
	@PostMapping("/addDataType")
	@ApiOperation(value = "新增数据字典类型", notes ="")
	public JsonObject<Object> addDataType(DataType obj,HttpServletRequest request){
		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
		//SwbAuthUser u=LoginAuthUser.getUserByAdminTest(request);
		obj.setUserID(u.getEntityID());//发布人id
		obj.setActiveStatus(BaseDataQuery.ACTIVESTATE_YES);
		obj.setLastModifyTime(new Date());
		if(u.getScopeCode()!=null) {
			obj.setOrgCode(u.getScopeCode());	
		}
		dataTypeService.addDataType(obj);
		return JsonUtil.success();
	}
	/*	typeID改为typeCode需要更改
	@GetMapping("/deleteDataType")
	@ApiOperation(value = "删除数据字典类型", notes = "")
	public JsonObject<Object> deleteDataType(@ApiParam(value = "typeID", required = true) @RequestParam("typeID") String typeID,HttpServletRequest request,HttpServletResponse response) throws Exception {
		DataTypeQuery query=new DataTypeQuery();
		query.setSearchParentTypeID(typeID);
		List<DataType> list=dataTypeService.getDataTypeList(query);
		if(null!=list && list.size()>0) {
			return JsonUtil.error("存在子分类，不能删除");
		}else {
			dataTypeService.deleteDataType(typeID);
			BaseDataQuery dataQuery=new BaseDataQuery();
			dataQuery.setSearchTypeID(typeID);
			List<BaseData> dataList=baseDataService.getBaseDataList(dataQuery);
			if(null!=dataList && dataList.size()>0) {
				baseDataService.deleteBaseDataByTypeCode(typeID);
			}
			return JsonUtil.success();
		}
	}*/
	@PostMapping("/updateDataType")
	@ApiOperation(value = "修改数据字典类型", notes ="")
	public JsonObject<Object> updateDataType(DataType obj,HttpServletRequest request){
		obj.setLastModifyTime(new Date());
		dataTypeService.updateDataType(obj);
		return JsonSuccessObject.SUCCESS;
	}	
	@GetMapping("/listDataType")
	@ApiOperation(value = "数据字典类型列表", notes ="")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchOrgID", value = "机构id", paramType = "query"),
	@ApiImplicitParam(name = "searchTypeID", value = "数据字典类型id", paramType = "query"),
	@ApiImplicitParam(name = "searchTypeCode", value = "数据字典类型code", paramType = "query")})
	public JsonQueryObject<DataType> listDataType(@ApiIgnore DataTypeQuery query,HttpServletRequest request){
//		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
		/*query.setSearchUserID(u.getEntityID());
		if(query.getSearchOrgID()==null || query.getSearchOrgID().equals("")) {
			query.setSearchOrgCode(u.getScopeCode());
		}*/
		List<DataType> list=dataTypeService.getDataTypeList(query);
/*		if(null!=list && list.size()>0) {
			for(DataType type:list) {
				int count=dataTypeService.getDataTypeCount(type.getTypeID());
				if(count>0) {
					type.setLeaf(true);
				}else {
					type.setLeaf(false);
				}
			}
		}*/
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@PostMapping("/addBaseDataOrg")
	@ApiOperation(value="新增字典与机构关联",notes="字典下发")
	public JsonObject<Object> addBaseDataOrg(BaseDataOrg baseDataOrg,HttpServletRequest request){
		if(baseDataOrg.getOrganizationIds()!=null&&baseDataOrg.getOrganizationIds().length>0) {
			SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
			//SwbAuthUser u=LoginAuthUser.getUserByAdminTest(request);
			baseDataOrg.setOperationUserId(u.getEntityID());
			baseDataOrgService.addBaseDataOrg(baseDataOrg);
			return JsonUtil.success("下发成功!");
		 }else {
				return JsonUtil.error("参数缺失");
			}
	}
	
}
